var login_user_infos;
var userId;
$(document).ready(function () {
    // ajax全局设置
    var submitMsgIndex;
    var ajaxSetting = {
        beforeSend: function (XMLHttpRequest, settings) {
            if (settings.type != 'GET') {
                submitMsgIndex = layer.msg('正在提交数据，请稍后...', {
                    shade: [0.2, '#393D49'],
                    time: 0
                });
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
            // session过期后，系统跳转到登录页
            if (XMLHttpRequest.status == 403) {
                var i = 3;
                var toLoginMsgIndex = layer.msg('登录失效，系统将在 '+i+' 秒后自动返回登录界面', {
                    id: 'sessionTimeOut-div',
                    shade: [0.2, '#393D49'],
                    time: 0
                });
                var interval = setInterval(function () {
                    if (i == 0) {
                        layer.close(toLoginMsgIndex);
                        window.location.href = '/index.html';
                        clearInterval(interval);
                    } else {
                        $('#sessionTimeOut-div').text('登录失效，系统将在 '+i+' 秒后自动返回登录界面');
                        i--;
                    }
                }, 1000);
            }
            if (submitMsgIndex) {
                layer.close(submitMsgIndex);
            }
        }
    }
    $.ajaxSetup(ajaxSetting);
    layui.jquery.ajaxSetup(ajaxSetting);
    var welcome_fn = {
        // 添加主页模块
        addWelcomeModule: function () {
            $('#modules').empty();
            $('#modules').append(
                '<li class="layui-nav-item layui-this">' +
                    '<a module-index="catalog-welcome" style="cursor: pointer">主页</a>' +
                '</li>'
            );
        },
        // 添加主页模块的菜单
        addWelcomeMenus: function () {
            var menu_welcome = '/piger/welcome.html' ;
            $.ajaxSettings.async = false;
            $.get('/cms/user/info/all?userId'+userId, function (data) {
                if (data.data.user_info.role == '2') {
                    menu_welcome = '/piger/applyUserWelcome.html';
                }else if (data.data.user_info.role == '3') {
                    menu_welcome = '/piger/companyWelcolme.html';
                }
            });
            $.ajaxSettings.async = true;
            $('#menus').empty();
            $('#menus').append(
                '<li class="layui-nav-item layui-nav-itemed">' +
                    '<a style="cursor: pointer">主页管理</a>' +
                    '<dl class="layui-nav-child">' +
                        '<dd>' +
                            '<a id="menu-welcome" cms-tab-url="'+menu_welcome+'" style="cursor: pointer;">欢迎页</a>' +
                        '</dd>' +
                    '</dl>' +
                '</li>'+
                '<li class="layui-nav-item layui-nav-itemed">' +
                    '<a style="cursor: pointer">求职市场</a>' +
                    '<dl class="layui-nav-child">' +
                        '<dd>' +
                            '<a id="menu-market" cms-tab-url="/piger/searchJob.html" style="cursor: pointer;">求职页</a>' +
                        '</dd>' +
                    '</dl>' +
                '</li>'
            );
            layui.element.render('nav', 'login-user-menus');
        }
    }
    // 初始化登录后的操作界面
    $.get('/cms/user/info/all?userId'+userId, function (data) {
        if (data.code == 200) {
            $('#login-user-name').append(data.data.user_info.name);
            login_user_infos = data.data;
            layui.each(login_user_infos.user_permissions, function (index, item) {
                if (index == 0) {
                    welcome_fn.addWelcomeModule();
                }
                if (item.type == 1) {
                    // 过滤掉小程序的菜单
                    if (item.systemId == 8) {
                        return;
                    }
                    $('#modules').append(
                        '<li class="layui-nav-item">' +
                            '<a module-index="'+index+'" style="cursor: pointer">'+item.name+'</a>' +
                        '</li>'
                    );
                }
            });
            layui.element.render('nav', 'login-user-modules');
            welcome_fn.addWelcomeMenus();
            if (data.data.user_info.role == '2') {
                cmsUtils.addContentTab($('#menu-welcome')[0].id, $('#menu-welcome')[0].textContent, '/piger/applyUserWelcome.html');
            }else if (data.data.user_info.role == '3') {
                cmsUtils.addContentTab($('#menu-welcome')[0].id, $('#menu-welcome')[0].textContent, '/piger/companyWelcolme.html');
            }else{
                cmsUtils.addContentTab($('#menu-welcome')[0].id, $('#menu-welcome')[0].textContent, '/piger/welcome.html');
            }
        }else{
            layer.msg(data.msg, {anim: 6});
        }
    });
    // 监听头部导航区域
    layui.element.on('nav(login-user-modules)', function (data) {
        $('#menus').empty();
        var module_index = data[0].getAttribute('module-index');
        console.log(module_index);
        if (module_index == 'catalog-welcome') {
            welcome_fn.addWelcomeMenus();
            return;
        }
        layui.each(login_user_infos.user_permissions[module_index].children, function (catalog_index, catalog_item) {
            var li_class = (catalog_index == 0) ? 'layui-nav-item layui-nav-itemed' : 'layui-nav-item';
            $('#menus').append(
                '<li class="'+li_class+'">' +
                    '<a style="cursor: pointer">'+catalog_item.name+'</a>' +
                    '<dl id="catalog'+catalog_item.id+'" class="layui-nav-child"></dl>' +
                '</li>'
            );
            layui.each(catalog_item.children, function (menu_index, menu_item) {
                $('#catalog'+menu_item.parentId).append(
                    '<dd>' +
                        '<a id="menu'+menu_item.id+'" cms-tab-url="'+menu_item.url+'" style="cursor: pointer">'+menu_item.name+'</a>' +
                    '</dd>'
                );
            });
        });
        layui.element.render('nav', 'login-user-menus');
    });
    // 监听左侧导航区域
    layui.element.on('nav(login-user-menus)', function (data) {
        if (data[0].id && data[0].getAttribute('cms-tab-url')) {
            cmsUtils.addContentTab(data[0].id, data[0].textContent, data[0].getAttribute('cms-tab-url'));
        }
    });
});
// 基本资料
function baseInfo() {
    $.get('/piger/baseInfo.html', function (data) {
        layer.open({
            type: 1,
            title: '<b>基本资料</b>',
            area: ['500px', '340px'],
            content: data,
            success: function () {
                $.get('/cms/user/info', function (data) {
                    if (data.code == 200) {
                        var role_name = '';
                        $.each(data.data.user_roles, function (index, item) {
                            if (index != (data.data.user_roles.length-1)) {
                                role_name += item.name+',';
                            } else {
                                role_name = role_name+item.name;
                            }
                        });
                        var form_data = {
                            username: data.data.user_info.username,
                            name: data.data.user_info.name,
                            roleName: role_name,
                            phone: data.data.user_info.phone
                        }
                        cmsUtils.formDataBind('baseInfo-form', form_data);
                    } else {
                        layer.msg(data.msg, {anim: 6});
                    }
                });
            }
        });
    });
}
// 修改密码
function editPwd() {
    $.get('/piger/editPwd.html', function (data) {
        layer.open({
            type: 1,
            title: '<b>修改密码</b>',
            area: ['500px', '300px'],
            content: data,
            success: function (layero, index) {
                // 自定义验证规则
                layui.form.verify({
                    newPwd: function (value) {
                        if (value.length < 4) {
                            return '密码长度为4~20位';
                        }
                    },
                    repNewPwd: function (value) {
                        var new_password = $('input[name=new_password]').val();
                        if (value != new_password) {
                            return '两次新密码输入不一致';
                        }
                    }
                });
                layui.form.on('submit(editPwd-btn-submit)', function (data) {
                    $.ajax({
                        type: 'post',
                        url: '/cms/editPWD',
                        data: data.field,
                        dataType: 'json',
                        success: function (data) {
                            if (data.code == 200) {
                                layer.close(index);
                            } else {
                                layer.msg(data.msg, {anim: 6});
                            }
                        }
                    });
                });
                $('#editPwd-btn-close').on('click', function () {
                    layer.close(index);
                });
            }
        });
    });
}
// 退出登录
function logout() {
    $.ajax({
        type: 'post',
        url: '/cms/logout',
        dataType: 'json',
        success: function (data) {
            if (data.code == 200) {
                window.location.href = '/index.html';
            } else {
                layer.msg(data.msg, {anim: 6});
            }
        }
    });
}